<template>
	<div>
		<el-form ref="form" :model="form" label-width="100px">
			<!--患者信息-->
			<el-form-item label="病案号"
						  prop="patient_id"
						  class="patient_id"
						  :rules="{ validator: checkPatient_id, trigger: 'blur' ,required:true}">
				<wt-patient-id-input :disabled="fixedPatient" v-model="form.patient_id" @select="onSelectPatient" style="width: 193px;display: inline-block;"></wt-patient-id-input>
				<el-alert
						v-if="isExistenceOFpatient"
						:title="'已找到病案号'+form.patient_id+'的患者信息'"
						type="info"
						class="tip"
						show-icon>
				</el-alert>
			</el-form-item>
			<el-form-item label="姓名"
						  prop="name"
						  :rules="[{ required: true, message: '请输入患者姓名', trigger: 'blur' }]">
				<el-input v-model="form.name" style="max-width: 193px" :disabled="disablePatientInfoEdit"></el-input>
			</el-form-item>
			<el-form-item label="性别"
						  prop="gender"
						  :rules="[{ required: true, message: '请选择患者性别',trigger: 'change'}]">
				<el-radio class="radio" v-model="form.gender" :label="genderValues[0]" :disabled="disablePatientInfoEdit">{{ genderText[0] }}</el-radio>
				<el-radio class="radio" v-model="form.gender" :label="genderValues[1]" :disabled="disablePatientInfoEdit">{{ genderText[1] }}</el-radio>
			</el-form-item>

			<el-form-item label="出生日期"
						  prop="patientBirthday"
						  :rules="[ { type: 'date', required: true, message: '请选择或输入出生日期', trigger: 'change' }]">
				<div class="date-picker">
					<el-date-picker
							v-model="form.patientBirthday"
							type="date"
							placeholder="选择出生日期"
							:disabled="disablePatientInfoEdit"
							:picker-options="datePickerOptions"
							@change="birth">
					</el-date-picker>
					<el-alert
							title="格式：xxxx-xx-xx，例如：2010-01-02"
							type="info"
							show-icon>
					</el-alert>
				</div>

			</el-form-item>
			<!--病例信息-->
			<el-form-item label="联系方式"
						  v-if="isShowCaseDetail"
						  prop="mobile"
                          :rules="{ validator:phone, trigger: 'blur' ,required:true}"
                          >
				<el-input v-model="form.mobile" style="max-width: 193px"></el-input>
			</el-form-item>
			<el-form-item label="所在地区" v-if="isShowCaseDetail">
                <wt-city-selector 
                    :province="form.address_value.selections[0]"
                    :city="form.address_value.selections[1]"
                    @change="onCitySelected"
                ></wt-city-selector><el-input style="width: 60%;" placeholder="请输入详细地址" v-model="form.address_value.address">
                </el-input>
			</el-form-item>
			<el-form-item label="诊断"
						  v-if="isShowCaseDetail"
						  prop="cases"
						  :rules="[{ type: 'array', required: true, message: '请至少选择一个诊断名称', trigger: 'change'}]">
				<wt-case-selector v-model="form.cases"></wt-case-selector>
			</el-form-item>
			<el-form-item label="上级医生"
						  v-if="isShowCaseDetail"
						  prop="supervisor_doctor_id"
						  :rules="[{ type: 'number', required: true, message: '请选择上级医生', trigger: 'change'}]">
				<el-tag v-if="iseditSupervisor()" type="primary" class="myselfname">{{myselfName}}</el-tag>
				<wt-select
						v-else
						v-model="form.supervisor_doctor_id"
						:multiple="false"
						:query="query"
						placeholder='请选择'
						:params-data="paramsData"
				></wt-select>
			</el-form-item>
			<el-form-item>
				<el-button v-if="!data.case_id" @click="onSubmit" icon="plus" type="primary" :loading="saving">创建并查看</el-button>
				<el-button v-else @click="onSubmit" icon="check" type="primary" :loading="saving">保存</el-button>
				<el-button v-if="!data.case_id"  @click="onSubmitAndNext()" icon="plus" :loading="saving">创建并添加下一个</el-button>
				<el-button @click="onCancel" icon="close">取消</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>
<script>
    /**
     * 编辑病例/患者信息组件，本组件支持以下使用场景：
     * - 新建病例，用户可以输入患者信息+病例信息
     * - 修改病例，用户不可以修改患者信息，但可以修改病例信息
     * - 为指定患者新建病例，用户不可以修改患者信息，但可以修改病例信息
     * - 修改患者基本信息，用户可以修改患者信息，修改后自动更新该患者对应的所有病例
     */
    import Vue from 'vue'
    import ElementUI from 'element-ui'
    import FormUtils from 'winged/utils/wt-form-utils'
    import PatientId from './wt-patient-id-input'
    import CaseSelector from './wt-case-selector'
    import CitySelector from './wt-city-selector'
    import request from 'winged/utils/axios'
    import Select from 'winged/components/wt-select'
    import Permissions from 'winged/utils/wt-permission'
    import times from 'winged/utils/wt-time-utils'
    import modelUtils from 'winged/utils/wt-model-utils'
    import moment from 'moment'
    
    Vue.use(ElementUI);
    Vue.component(PatientId.name, PatientId);
    Vue.component(CaseSelector.name, CaseSelector);
    Vue.component(CitySelector.name, CitySelector);
    Vue.component(Select.name, Select);

    function createDefaultForm() {
        return {
            'name': '',
            'patient_id': '',
            'mobile': '',
            'cases': [],
            'gender': FormUtils.getMaleValue(),
            'address': '',
            'doctor_advice': '',
            'present_history': '',
            'imaging_exam_no': '',
            'province_id': '',
            'city_id': '',
            'case_id':'',
            'address_value' : {
                selections: [],
                address: ''
            },
            'supervisor_doctor_id':'',
            'patientBirthday': null,
        }
    }
    export default {
        name: 'wt-patient-form',
        props:{
            data: {
                type: Object,
                default: function() {
                    return createDefaultForm();
                }
            },
            action: {
                type: Number,
                required: true,
            }
        },
        watch: {
        },
        data() {
            return {
                form: this.data,
                genderValues: FormUtils.genderOptions,
                genderText: FormUtils.genderText,
                caseId: '',
                saving: false,
                // 经过查询并且用户选择后的患者病案号
                currentExistingPatientId: null,
                query: {
                    method: 'GET',
                    url: 'doctor/supervisors',
                    transfer: true,
                    label: 'name',
                    value: 'id',
					extraParams:['doctor_id']
                },
                old_patient_id:this.data.patient_id,
                isSupervisor: Permissions.isCurrentUserManager(),
                myselfName: Permissions.getCurrentUserName(),
                // 查询患者病案号有关的提示信息
                searchingMessage: '',
                paramsData: {
					doctor_id: this.data.creator_doctor_id?this.data.creator_doctor_id:''
                },
                datePickerOptions:{
                    disabledDate(time){
                        //利用现在的时间计算今天结束时的时间
                        let now = new Date(),
                            y = now.getFullYear(),
                            m = now.getMonth(),
                            d = now.getDate(),
                            todayEndTime = new Date(y,m,d).getTime(),//今天结束时的时间
                            inputDate = time.getTime()
						if(inputDate > todayEndTime){
                            return true
						}else{
						    return false
						}
					}
				}
            }
        },
        computed: {
			hasNewPatientId:function(){
				return this.form.patient_id != this.origin_patient_id;
			},
            isExistenceOFpatient:function(){
                if(this.hasNewPatientId){
                    return this.fixedPatient || this.currentExistingPatientId == this.form.patient_id;
                }
                return  false;
            },
            disablePatientInfoEdit: function() {
                let res;
                switch(action){
                    case 0://新建病例
                        res =  this.fixedPatient || this.currentExistingPatientId == this.form.patient_id;
                    	break;
                    case 1://患者编辑
                    case 2://病例编辑
                        res =  this.fixedPatient;
                        break;
                    default:
                        console.error("action：意料之外的值")
                }
                return res;
            },
            // 是否是为指定的患者添加病例（不可以修改患者信息）
            fixedPatient: function() {
                let res;
                switch(action){
                    case 0://新建病例
                        if(!!this.origin_patient_id){//如果最开始有patient_id字段，则为为指定患者新建病例
                            res =  true;
                        }else{//完全新建病例
                            res = false;
                        }
                        break;
                    case 1://患者编辑
                        res =  false;
                        break;
                    case 2://病例编辑
                        res =  true;
                        break;
                    default:
                        console.error("action：意料之外的值")
                }
                return res;
            },
			/*
			 * isShowCaseDetail： 是否显示病例信息（让用户编辑）
			 * action 0：新建患者信息，1：患者详情编辑，2：病例详情编辑
			 **/
            isShowCaseDetail:function(){
                return action == 2 || action == 0
            }
        },
        methods: {
            checkPatient_id:function(prop,val,callback){
                //case- 1 病案号没有变化
                if(val == this.origin_patient_id){
                    callback()
				}
                //case- 2 病案号为空
                if(val.trim() == ''){
                    callback(new Error('必须填写病案号！'))
				}
                //case- 3 病案号改变
				if(this.isExistenceOFpatient){
                    if(action != 1){
                        callback()
                    }else{
                        callback(new Error('病案号已存在'))
                    }

				}else{
                    callback()
				}
			},
             phone:function(prop,phone,callback){
                if(phone === ""){
                    callback(new Error('请输入联系方式'));
                }
                if(/^\d+$/.test(phone)){
                    callback()
                }else{
                    callback(new Error('电话号码格式错误，请重新输入'));
                }
            //    if (/^1(3|4|5|7|8)\d{9}$/.test(phone)){
			// 		callback()
			// 	}else {
			// 		callback(new Error('电话号码格式错误，请重新输入'));
			// 	}
            },
            formatForm: function() {
                if (this.form.patientBirthday) {
                    this.form.patientBirthday = times.toDate(this.form.patientBirthday);
                }
            },
            onSubmitAndNext: function() {
                let vm = this;
                this.doSubmit(function () {
                    // 清空表单，清空caseId，准备添加下一个
                    vm.form = createDefaultForm();
                });
            },
            onSubmit: function() {
                let vm=this;
                this.doSubmit(function () {
                    /*
                    * case-1:新建病例和编辑病例后，跳转到病例详情页
                    * case-2：编辑患者后跳转到患者详情
                    * */
                    switch(action){
                        case 0://新建病例
                        case 2://病例编辑
                            window.location.href = '/admin/patients/case/'+vm.caseId;
                            break;
                        case 1://患者编辑
                            window.location.href = '/admin/patients/show?case_id=' + vm.caseId + "&" +"patient_id=" + vm.patient_id;
                            break;
                        default:
                            console.error("action：意料之外的值")
                    }

                });
            },
            onCitySelected(val) {
                this.form.address_value.selections[0] = val[0];
                this.form.address_value.selections[1] = val[1];
            },
            onCancel: function() {
//                this.form = createDefaultForm();
                window.history.go(-1);
            },
            doSubmit: function(callback) {
                require('winged/utils/axios');
                var vm = this;
                if (vm.isSupervisor&&action!=2){
                    vm.form.supervisor_doctor_id = Permissions.getCurrentUserId();
                };
                vm.$refs.form.validate((valid) => {
                    if (valid) {
                        vm.form.birthday = times.format(vm.form.patientBirthday);
                        vm.form.province_id = vm.form.address_value.selections[0];
                        vm.form.city_id = vm.form.address_value.selections[1];
                        vm.form.address = vm.form.address_value.address;
                        // case_name需要以json格式传输
                        vm.form.case_name = JSON.stringify(vm.form.cases);
                        vm.saving = true;
                        // action - 0
                        if (action == 0){
                            var call=window.axios.post('patients/case/create', {data: vm.form});
                        }
                        // action - 1
                        else if(action == 1){
                            let data = modelUtils.cloneObject(vm.form);
                            data.patient_id = vm.old_patient_id;
                            data.new_patient_id = vm.form.patient_id;
                            var call = window.axios.put('patients/update', data);
                        }else if(action == 2){
                            var call=window.axios.put(`patients/case/${vm.data.case_id}`, {data: vm.form});
                        }
                        // action - 2

                        call.then(function(response){
                            vm.saving = false;
                            if (response.status == 200)  {
                                let data = response.data;
                                // 获取新的case id并保存到vm.caseId
                                console.log(data)
                                vm.caseId = data.patientCaseId || data.id;
                                // 获取新的patient_id并保存到vm.patient_id
                                vm.patient_id = data.patientId;
                                // 弹出提示
                                if (data == ""){
                                    vm.$message.error('保存失败');
                                }
                                else {
                                    vm.$message.success('保存成功');
                                    callback && callback();
//									let path ='doctor/patient/case/count';
//									let occupy = {patient_id:data.patientId};
//									request(path, 'GET', occupy, true, function(dt) {
//										if (typeof (dt) == 'string'){
//											dt = JSON.parse(dt)
//										}
//										if (dt.count > 1){
//											vm.$confirm('此条病例已修改成功。该患者有多条病例，是否确定将信息更新到该患者的所有病例（诊断信息除外）？', '操作提示', {
//												confirmButtonText: '确定',
//												cancelButtonText: '取消',
//												type: 'warning'
//											}).then(() => {
//												let message = vm.form;
//												request('patients/update', 'put', message, false, function(rerult) {
//													vm.$message.success('更新成功');
//												}, function(error) {
//													vm.$message.error('更新失败')
//												});
//												callback();
//											}).catch(() => {
//												callback();
//											});
//										}else {
//											callback();
//										}
//									}, function(error) {
//										vm.$message.error('查询失败')
//									});
                                }
                            }
                            else {
                                vm.saving = false;
                                // 错误提示
                                vm.$message.error('提交失败')
                            }
                        }).catch(function(error){
                            // 进行错误提示
                            vm.$message.error('提交失败')
                        });
                    }

                });
            },
            onSelectPatient: function(data) {
                this.currentExistingPatientId = this.form.patient_id;
                //为指定患者新建病例
                if(action != 1){
                    //填充表单
                    this.fullForm(data);
                    //如果有日期，生日等，则格式化
                    this.formatForm();
				}else{
                    //验证病案号
                    this.$refs.form.validateField('patient_id');
				}
            },
			fullForm:function(data){
                this.form.name = data.patientName;
                this.form.gender = data.patientGender;
                this.form.mobile = data.mobile;
                this.form.address_value.selections[0] = data.provinceId;
                this.form.address_value.selections[1] = data.cityId;
                this.form.address_value.address = data.patientBirthplace;
                this.form.patientBirthday = data.patientBirthday;
			},
            birth:function () {
                let current = moment();
                let birthday = moment(this.form.patientBirthday);
            },
			iseditSupervisor(){
				if ((this.isSupervisor&&action!=2)){
					return true
				}else if (this.data.supervisor_doctor_id==this.data.creator_doctor_id&&action==2){
					this.myselfName = this.form.creator_doctor_name;
					return true
				}else {
					return false
				}
			}
        },
        created(){
        	console.log(this.form)
            var vm=this;
            //用origin_patient_id保存最开始的patient_id,以防patient_id被意外修改
            vm.origin_patient_id = vm.data.patient_id;
            if(this.data.hasOwnProperty('case_id')){
                this.form.cases = JSON.parse(this.data.cases);
            }else if(this.fixedPatient){
                this.form.fixedPatient = this.fixedPatient;
                vm.form = createDefaultForm();
                vm.form.patient_id = this.data.patient_id;
                let axios = require('winged/utils/axios');
                let path = `doctor/patient/existed/${patient_id}`;
                window.axios.wtCall(path, 'GET').then(function (response) {
                    let data = response.data.content;
                    if(typeof(data) == 'string') {
                        data = JSON.parse(data);
                    }
                    vm.onSelectPatient(data[0]);
                })
            }
            else {
                this.form = createDefaultForm();
            }
            this.formatForm();
        },
    }
</script>
<style scoped>
	.el-form{
		max-width: 800px;
	}
	.myselfname{
		height: 30px;
		min-width: 60px;
		text-align: center;
		line-height: 26px;
		font-size: 16px;
		padding: 0 10px;
	}
	.patient_id>.el-form-item__content>div,
	.date-picker>div{
		float:left;
	}
	.patient_id .wt-patient-id-input,
	.date-picker>.el-date-editor{
		margin-right:10px;
		margin-bottom:10px;
	}
	.date-picker>.el-alert{
		max-width:340px;
		width:100%;
		padding:0 16px;
	}
	.patient_id .el-alert{
		max-width:270px;
		width:100%;
		padding:0 16px;
	}
</style>